
var websock = null
var lockReconnect = false //是否真正建立连接
var timeoutnum = null //断开 重连倒计时
var timeout = 30 * 1000//30秒一次心跳
var timeoutObj = null //心跳心跳倒计时
var serverTimeoutObj = null //心跳倒计时
var isDestoryed = false
var wsUri = "ws://127.0.0.1:4000"
var nodeRecTime = ""
var content = ''

function initWebSocket(wsuri) {
    if (isDestoryed) return;
    //初始化weosocket
    if (websock) {
        websock.close()
    }
    // const wsuri = "ws://localhost:3000/"; //ws地址
    if (!wsuri) return;
    websock = new WebSocket(wsuri);
    websock.onopen = websocketonopen;
    websock.onerror = websocketonerror;
    websock.onmessage = websocketonmessage;
    websock.onclose = websocketclose;//
}

function websocketonopen() {
    console.log("WebSocket连接成功");
    sendMessage();
    //开始心跳检测
    start();
}

function websocketonerror(e) {
    //错误
    console.log("WebSocket连接发生错误:" + e);
    reconnect();
}

function websocketonmessage(e) {
    //数据接收
    let data = JSON.parse(e.data);
    // console.log(data.content.msg);
    if (data.content.msg) {
        // // ws
        // renderFromWs(data.content.msg)
        // ws + 渐变
        renderFromWsLinear(data.content.msg)
    }
    //接收到信息后重置心跳检测
    reset();
}

function websocketclose() {
    if (isDestoryed) return;
    //关闭
    console.log("connection closed");
    //准备重连
    console.log("准备重连了");
    reconnect();
}

function reconnect() {
    //重新连接
    console.log("开始重连1");
    if (lockReconnect) {
        return;
    }
    console.log("开始重连2");
    lockReconnect = true;
    //没连接上会一直重连，设置延迟避免请求过多
    timeoutnum && clearTimeout(timeoutnum);
    timeoutnum = setTimeout(function () {
        //新连接
        initWebSocket(wsUri);
        console.log("开始重连3");
        lockReconnect = false;
    }, 5000);
}

function reset() {
    //重置心跳
    var that = this;
    //清除时间
    clearTimeout(that.timeoutObj);
    clearTimeout(that.serverTimeoutObj);
    //重启心跳
    that.start();
}

function start() {
    //开启心跳
    var self = this;
    self.timeoutObj && clearTimeout(self.timeoutObj);
    self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
    self.timeoutObj = setTimeout(function () {
        //这里发送一个心跳，后端收到后，返回一个心跳消息，
        if (self.websock.readyState == 1) {
            //如果连接正常
            self.websock.send(JSON.stringify({
                cmd: "heart",
                content: {}
            }));
        } else {
            //否则重连
            self.reconnect();
        }
        self.serverTimeoutObj = setTimeout(function () {
            //超时关闭
            self.websock.close();
        }, self.timeout);
    }, self.timeout);
}

function sendMessage() {
    console.log(1);
    websock.send(JSON.stringify({
        cmd: "port",
        content: { devicePort: 1026 }
    }));
}


initWebSocket(wsUri);